﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using TruckingApplication.Dal.EntityModels;
using TruckingApplication.Common;

namespace TruckingApplication.Web.Controllers
{ 
    public class ResourceController : Controller
    {
        private TRUCKING_FRAMEWORK_Entities_2 db = new TRUCKING_FRAMEWORK_Entities_2();

        //
        // GET: /Resource/

        public ViewResult Index()
        {
            var resources = db.RESOURCEs.Include(r => r.RESOURCE_TYPE);
            return View(resources.ToList());
        }

        //
        // GET: /Resource/Details/5

        public ViewResult Details(long id)
        {
            RESOURCE resource = db.RESOURCEs.Find(id);
            return View(resource);
        }

        //
        // GET: /Resource/Create

        public ActionResult Create()
        {
            ViewBag.resourceTypeID = new SelectList(db.RESOURCE_TYPE, "resourceTypeID", "resourceType");
            ViewBag.trailerTypeID = new SelectList(db.TRAILER_TYPE, "trailerTypeID", "type");

            var _s = from s in db.STATEs select s;
            var stateList = new List<string>();
            foreach (var s in _s)
            {
                stateList.Add(s.sateAbv);
            }

            var states = new SelectList(stateList);

            ViewBag.States = states;

            return View();
        } 

        //
        // POST: /Resource/Create

        [HttpPost]
        public ActionResult Create(RESOURCE resource, FormCollection collection)
        {
            if (ModelState.IsValid)
            {
                var emailSplit = resource.email.Split(new string[] {"@"},StringSplitOptions.RemoveEmptyEntries);
                var defaultUserName = collection["firstName"] + "_" + collection["lastName"] + "_" + emailSplit[0];

                // Create .NET User
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(defaultUserName, resource.email, resource.email, null, null, true, null, out createStatus);
                Roles.AddUserToRole(defaultUserName, "End-user");
                if (createStatus == MembershipCreateStatus.Success)
                {
                    //resource.parentCompanyId = Dal.Infrastructure.UserSpecifics.CompanyID;
                    //Dal.Infrastructure.UserSpecifics.Email = resource.email;
                    // Add Resource
                    resource.FullName = resource.firstName + " " + resource.lastName;
                    resource.isActive = true;
                    resource.parentCompanyId = Dal.Infrastructure.UserSpecifics.CompanyID;
                    resource.state = collection["States"];
                    db.RESOURCEs.Add(resource);
                    db.SaveChanges();

                    // Add Resource Company
                    var newResourceID = db.RESOURCEs.Where(r => r.email == resource.email).SingleOrDefault().resourceID;
                    var resouceCompany = new RESOURCE_COMPANY
                    {
                        companyID = Dal.Infrastructure.UserSpecifics.CompanyID,
                        resourceID = newResourceID
                    };

                    try
                    {
                        db.RESOURCE_COMPANY.Add(resouceCompany);
                        db.SaveChanges();
                    }
                    catch (DbEntityValidationException dbEx)
                    {
                        foreach (var validationErrors in dbEx.EntityValidationErrors)
                        {
                            foreach (var validationError in validationErrors.ValidationErrors)
                            {
                                Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                            }
                        }
                    }

                    try
                    {
                        //Check if Trailer
                        var trailer = new TRAILER
                        {
                            vin = collection["Vin"],
                            mileage = int.Parse(collection["Miles"]),
                            trailerTypeID = int.Parse(collection["trailerTypeID"]),
                            resourceID = newResourceID
                        };

                        db.TRAILERs.Add(trailer);
                        db.SaveChanges();

                        if (collection["ins"].ToLower() == "yes")
                        {
                            // determine end date
                            var length = collection["ddl_insLgth"] == "6 Months" ? 6 : 12;
                            var startDate = DateTime.Parse(collection["tb_insStartDate"]);
                            var endDate = startDate.AddMonths(length);

                            var insurance = new INSURANCE
                            {
                                trailerID = trailer.trailerID,
                                startDate = startDate,
                                endDate = endDate,
                                total = Decimal.Parse(collection["tb_totalPaymentAmt"]),
                                paymentTerms = collection["paymentTerms"],
                                paymentAmount = Decimal.Parse(collection["paymentAmount"])
                            };
                            db.INSURANCEs.Add(insurance);
                            db.SaveChanges();
                        }
                        // TODO: Need to determine how these values are calculated...
                        if (collection["ra"].ToLower() == "yes")
                        {
                            var roadAsst = new ROADSIDE_ASSISTANCE
                            {
                                trailerID = trailer.trailerID,
                                startDate = DateTime.Now,
                                endDate = DateTime.Now.AddMonths(6),
                                total = 500.00M,
                                paymentTerms = collection["paymentTerms"],
                                paymentAmount = 150.00M,
                            };
                            db.ROADSIDE_ASSISTANCE.Add(roadAsst);
                            db.SaveChanges();
                        }
                    }catch (Exception err){}
                    
                    // Send welcome email
                    var returnURL = "http://yourSubDomain.myHost.com/Login/";
                    var link = "<a href=\""+returnURL+"\">click here</a>";
                    Utils.SendEmail(resource.email, "", "", "You have been registered.",
                        "Your account was created.  Your username is " + 
                        defaultUserName + ".  Your password is your email address.  To access the site, " + 
                        link + ". (or copy & paste into your browser '')");

                    return RedirectToAction("Dashboard", "Account"); 
                }
                 
            }

            ViewBag.resourceTypeID = new SelectList(db.RESOURCE_TYPE, "resourceTypeID", "resourceType", resource.resourceTypeID);
            return View(resource);
        }
        
        //
        // GET: /Resource/Edit/5
 
        public ActionResult Edit(long id)
        {
            RESOURCE resource = db.RESOURCEs.Find(id);
            ViewBag.resourceTypeID = new SelectList(db.RESOURCE_TYPE, "resourceTypeID", "resourceType", resource.resourceTypeID);

            var _s = from s in db.STATEs select s;
            var states = new SelectList(_s, "sateAbv", "sateAbv", resource.state);

            ViewBag.States = states;
            ViewBag.SelectedState = resource.state;

            return View(resource);
        }

        //
        // POST: /Resource/Edit/5

        [HttpPost]
        public ActionResult Edit(RESOURCE resource, FormCollection collection)
        {
            if (ModelState.IsValid)
            {
                resource.state = collection["States"];
                resource.FullName = resource.firstName + " " + resource.lastName;
                resource.isActive = true;
                db.Entry(resource).State = EntityState.Modified;
                db.SaveChanges();
                //return RedirectToAction("Index");
                return RedirectToAction("Dashboard", "Account");
            }
            ViewBag.resourceTypeID = new SelectList(db.RESOURCE_TYPE, "resourceTypeID", "resourceType", resource.resourceTypeID);
            return View(resource);
        }

        //
        // GET: /Resource/Delete/5
 
        public ActionResult Delete(long id)
        {
            RESOURCE resource = db.RESOURCEs.Find(id);
            return View(resource);
        }

        //
        // POST: /Resource/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(long id)
        {            
            RESOURCE resource = db.RESOURCEs.Find(id);
            resource.isActive = false;
            //db.RESOURCEs.Remove(resource);
            db.Entry(resource).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Dashboard", "Account");
            //return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        #region Subscriber Specific Methods

        public ActionResult OurResources()
        {
            var resourcesForMyCompany =
                db.RESOURCE_COMPANY.Where(
                    rc => rc.companyID == Dal.Infrastructure.UserSpecifics.CompanyID).Include(r => r.RESOURCE).Include(x => x.RESOURCE.RESOURCE_TYPE);

            //var resources = db.RESOURCEs.Include(r => r.RESOURCE_TYPE).Include(c => c.RESOURCE_COMPANY);

            return View(resourcesForMyCompany);
        }

        #endregion

        public void TestWCFService()
        {
            
        }
    }
}